package com.zyk.leetcode;

/**
 * @author zhangsan
 * @date 2021/4/4 19:03
 */
public class J24 {

        public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    /** https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/ */
    public static ListNode mergeTwoLists(ListNode A, ListNode B) {
        ListNode left = A;
        ListNode right = B;

        ListNode newList = new ListNode(0);
        ListNode help = newList;

        while (left != null && right != null) {
            if(left.val <= right.val) {
                help.next = left;
                left = left.next;
            }else {
                help.next = right;
                right = right.next;
            }
            help = help.next;
        }
        help.next = left != null ? left: right;
        return newList.next;
    }


    // for test
    public static void printList(ListNode head) {
        if(head == null) {
            return;
        }
        ListNode cur = head;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();
    }

    // for test
    public static void main(String[] args) {
        ListNode A = new ListNode(1);
        A.next = new ListNode(2);
        A.next.next = new ListNode(4);

        ListNode B = new ListNode(1);
        B.next = new ListNode(3);
        B.next.next = new ListNode(4);
        printList(A);
        printList(B);

        ListNode newList = mergeTwoLists(A, B);

        printList(newList);
    }

}
